package com.rc.saas.tenant.service.enterprise;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberOutMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberRecordMapper;
import com.rc.saas.tenant.model.channel.RcChannelApply;
import com.rc.saas.tenant.model.enterprise.*;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberAccountRecord;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.MemberInfoExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberSearch;
import com.rc.saas.tenant.service.channel.RcChannelApplyService;
import com.rc.saas.tenant.service.member.MemberAccountRecordService;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.vo.enterprise.EnterPriseSubMemberResult;
import com.rc.saas.tenant.vo.enterprise.EnterpriseSubmemberExportVo;
import com.rc.saas.tenant.vo.enterprise.EnterpriseSubmemberOutResult;
import com.rc.saas.tenant.vo.enterprise.EnterpriseSubmemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author frog
 * @date 2021/2/6
 */
@Service
public class EnterpriseSubmemberServiceImpl implements EnterpriseSubmemberService {

    @Autowired
    private EnterpriseSubmemberMapper enterpriseSubmemberMapper;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private EnterpriseSubmemberRecordMapper enterpriseSubmemberRecordMapper;

    @Autowired
    private EnterpriseSubmemberOutMapper enterpriseSubmemberOutMapper;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private RcChannelApplyService channelApplyService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private MqProducer mqProducer;


    @Override
    public EnterpriseSubmemberMapper getMapper() {
        return enterpriseSubmemberMapper;
    }

    @Override
    public TResponse updateStatus(Long memberId) {
        EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberMapper.selectByPrimaryKey(memberId);
        EnterpriseMemberExample enterpriseMemberExample=new EnterpriseMemberExample();
        enterpriseMemberExample.createCriteria().andEnterpriseIdEqualTo(enterpriseSubmember.getBelongEnterpriseId());
        List<EnterpriseMember> enterpriseMembers=enterpriseMemberMapper.selectByExample(enterpriseMemberExample);
        //查看子账户是否冻结
        MemberInfo subMemberInfo=memberInfoService.selectByPrimaryKey(memberId);
        if (!CollectionUtils.isEmpty(enterpriseMembers)){
            //查看对应主账户是否冻结
            MemberInfo enterpriseMemberInfo=memberInfoService.selectByPrimaryKey(enterpriseMembers.get(0).getMemberId());
            if (enterpriseMemberInfo!=null ||subMemberInfo!=null){
                if ("1".equals(enterpriseMemberInfo.getStatus()) && "2".equals(enterpriseSubmember.getStatus())) {
                    return TResponse.FAIL("主会员被冻结，企业子会员无法解冻");
                } else if ("1".equals(enterpriseMembers.get(0).getStatus())&& "2".equals(enterpriseSubmember.getStatus())) {
                    return TResponse.FAIL("主会员被冻结，企业子会员无法解冻");
                } else if ("1".equals(subMemberInfo.getStatus()) && "2".equals(enterpriseSubmember.getStatus())){
                    return TResponse.FAIL("该会员被冻结，企业子会员无法解冻");
                } else if ("0".equals(enterpriseMemberInfo.getStatus()) && "2".equals(enterpriseSubmember.getStatus())){
                    enterpriseSubmember.setStatus("0");
                } else if ("0".equals(enterpriseMemberInfo.getStatus()) && "0".equals(enterpriseSubmember.getStatus())){
                    enterpriseSubmember.setStatus("2");
                } else if ("0".equals(subMemberInfo.getStatus()) && "2".equals(enterpriseSubmember.getStatus())){
                    enterpriseSubmember.setStatus("0");
                } else if ("0".equals(subMemberInfo.getStatus()) && "0".equals(enterpriseSubmember.getStatus())){
                    enterpriseSubmember.setStatus("2");
                }
            }
        }
        enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember);
        return TResponse.SUCCESS();
    }

    @Override
    public TResponse updateLogout(Long memberId) {
        updateRecoveredAmount(memberId);

        EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberMapper.selectByPrimaryKey(memberId);

        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmember.getBelongEnterpriseId());

        EnterpriseSubmemberRecord enterpriseSubmemberRecord = new EnterpriseSubmemberRecord();
        enterpriseSubmemberRecord.setTenantCode(enterpriseSubmember.getTenantCode());
        enterpriseSubmemberRecord.setSubMemberId(enterpriseSubmember.getMemberId());
        enterpriseSubmemberRecord.setEnterpriseMemberId(enterpriseMember.getMemberId());
        enterpriseSubmemberRecord.setEnterpriseId(enterpriseMember.getEnterpriseId());
        // //记录类型 0 子会员申请成功 1子会员注销成功 2运营商分配 3运营商注销 4.运营商还原 默认0
        // if ("0".equals(enterpriseSubmember.getStatus())) {
        //     enterpriseSubmemberRecord.setRecordType("3");
        //     //状态(0正常 1注销 2冻结) 默认 0
        //     enterpriseSubmember.setStatus("1");
        // } else if ("1".equals(enterpriseSubmember.getStatus())) {
        //     enterpriseSubmemberRecord.setRecordType("4");
        //     //状态(0正常 1注销 2冻结) 默认 0
        //     enterpriseSubmember.setStatus("0");
        // }
        Date date = new Date();

        enterpriseSubmemberRecordMapper.insertSelective(enterpriseSubmemberRecord);

        //状态(0正常 1注销 2冻结) 默认 0
        enterpriseSubmember.setStatus("1");
        enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember);

        EnterpriseSubmemberOut enterpriseSubmemberOut = new EnterpriseSubmemberOut();
        enterpriseSubmemberOut.setBelongEnterpriseId(enterpriseMember.getEnterpriseId());
        enterpriseSubmemberOut.setSubmemberId(memberId);
        enterpriseSubmemberOut.setOutTime(date);
        enterpriseSubmemberOut.setTenantCode(enterpriseSubmember.getTenantCode());
        enterpriseSubmemberOutMapper.insertSelective(enterpriseSubmemberOut);

        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
        memberInfo.setMemberType("0");
        memberInfo.setBelongEnterpriseId(null);
        memberInfo.setEnterpriseMemberId(null);
        memberInfoService.updateByPrimaryKey(memberInfo);
        return TResponse.SUCCESS();
    }

    @Override
    public TResponse updateReductionSubMember(Long submemberOutId) {
        EnterpriseSubmemberOut enterpriseSubmemberOut = enterpriseSubmemberOutMapper.selectByPrimaryKey(submemberOutId);
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(enterpriseSubmemberOut.getSubmemberId());
        if (!"0".equals(memberInfo.getMemberType())) {
            return TResponse.FAIL("该会员已不是普通会员,不能还原");
        }
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmemberOut.getBelongEnterpriseId());

        EnterpriseSubmember enterpriseSubmember = new EnterpriseSubmember();
        enterpriseSubmember.setMemberId(enterpriseSubmemberOut.getSubmemberId());
        enterpriseSubmember.setTenantCode(enterpriseSubmemberOut.getTenantCode());
        enterpriseSubmember.setBelongEnterpriseId(enterpriseSubmemberOut.getBelongEnterpriseId());
        enterpriseSubmember.setStatus("0");
        enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember);

        memberInfo.setMemberType("2");
        memberInfo.setBelongEnterpriseId(enterpriseMember.getEnterpriseId());
        memberInfo.setEnterpriseMemberId(enterpriseMember.getMemberId());
        memberInfoService.updateByPrimaryKeySelective(memberInfo);

        enterpriseSubmemberOut.setStatus("1");
        enterpriseSubmemberOutMapper.updateByPrimaryKeySelective(enterpriseSubmemberOut);
        return TResponse.SUCCESS();
    }

    @Override
    public TResponse updateRecoveredAmount(Long memberId) {
        MemberAccount subMemberAccount = memberAccountService.selectByPrimaryKey(memberId);
        MemberInfo subMemberInfo = memberInfoService.selectByPrimaryKey(memberId);

        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(subMemberInfo.getBelongEnterpriseId());

        MemberAccount enterpriseAccountInfo = memberAccountService.selectByPrimaryKey(enterpriseMember.getMemberId());


        BigDecimal enterpriseAccount = subMemberAccount.getEnterpriseAccount();
        BigDecimal result = new BigDecimal(0);

        /**
         * 增加子会员记录
         */
        MemberAccountRecord subMemberAccountRecord = new MemberAccountRecord();
        subMemberAccountRecord.setTenantCode(subMemberAccount.getTenantCode());
        subMemberAccountRecord.setMemberId(subMemberInfo.getMemberId());
        subMemberAccountRecord.setAccountType("1");
        //记录类型(0会员在线充值,1支出,2转账收入,3转账支出,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移)
        subMemberAccountRecord.setRecordType("7");
        subMemberAccountRecord.setRemark("回收金额");
        subMemberAccountRecord.setAmount(enterpriseAccount);
        subMemberAccountRecord.setResult(result);
        memberAccountRecordService.insertSelective(subMemberAccountRecord);

        /**
         * 增加主会员记录
         */
        MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
        memberAccountRecord.setTenantCode(subMemberAccount.getTenantCode());
        memberAccountRecord.setMemberId(enterpriseMember.getMemberId());
        memberAccountRecord.setAccountType("1");
        //记录类型(0会员在线充值,1支出,2转账收入,3转账支出,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移)
        memberAccountRecord.setRecordType("7");
        memberAccountRecord.setRemark("回收金额");
        memberAccountRecord.setAmount(enterpriseAccount);
        memberAccountRecord.setResult(enterpriseAccountInfo.getEnterpriseAccount().add(enterpriseAccount));
        memberAccountRecordService.insertSelective(memberAccountRecord);

        enterpriseAccountInfo.setEnterpriseAccount(enterpriseAccountInfo.getEnterpriseAccount().add(enterpriseAccount));
        memberAccountService.updateByPrimaryKeySelective(enterpriseAccountInfo);

        subMemberAccount.setEnterpriseAccount(new BigDecimal(0));
        memberAccountService.updateByPrimaryKeySelective(subMemberAccount);

        return TResponse.SUCCESS();
    }

    @Override
    public EnterpriseSubmember selectEnterpriseSubmemberByMigrateId(String tenantCode, Long migrateId) {
        EnterpriseSubmemberExample example = new EnterpriseSubmemberExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andMigrateIdEqualTo(migrateId);
        List<EnterpriseSubmember> list = enterpriseSubmemberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public PageInfo<EnterpriseSubmemberOutResult> listLogout(EnterpriseSubMemberSearch enterpriseSubMemberSearch) {
        PageHelper.startPage(enterpriseSubMemberSearch.getOffset(), enterpriseSubMemberSearch.getLimit());
        List<EnterpriseSubmemberOutResult> enterPriseSubMemberResults = enterpriseSubmemberOutMapper.listLogout(enterpriseSubMemberSearch);
        return new PageInfo<EnterpriseSubmemberOutResult>(enterPriseSubMemberResults);
    }

    @Override
    public PageInfo<EnterPriseSubMemberResult> searchByCondition(EnterpriseSubMemberSearch enterpriseSubMemberSearch) {
        PageHelper.startPage(enterpriseSubMemberSearch.getOffset(), enterpriseSubMemberSearch.getLimit());
        List<EnterPriseSubMemberResult> subMemberResults = enterpriseSubmemberMapper.searchByCondition(enterpriseSubMemberSearch);
        return new PageInfo<EnterPriseSubMemberResult>(subMemberResults);
    }

    @Override
    public List<Long> listMemberIdByEnterpriseId(String tenantCode, Long enterpriseId) {
        List<Long> subMemberIdList = enterpriseSubmemberMapper.listMemberIdByEnterpriseId(tenantCode, enterpriseId);
        return subMemberIdList;
    }

    @Override
    public List<EnterpriseSubmemberExportVo> listEnterpriseSubmember(EnterpriseSubMemberSearch enterpriseSubMemberSearch) {
        List<EnterpriseSubmemberExportVo> list = enterpriseSubmemberMapper.listEnterpriseSubmember(enterpriseSubMemberSearch);
        return list;
    }

    @Override
    public EnterpriseSubmember selectMemberByMemberId(Long memberId) {
        EnterpriseSubmemberExample enterpriseSubmemberExample=new EnterpriseSubmemberExample();
        enterpriseSubmemberExample.createCriteria().andMemberIdEqualTo(memberId);
        List<EnterpriseSubmember> enterpriseSubmembers=enterpriseSubmemberMapper.selectByExample(enterpriseSubmemberExample);
        if (!CollectionUtils.isEmpty(enterpriseSubmembers)){
            return enterpriseSubmembers.get(0);
        }
        return null;
    }

    @Override
    public void updateSubmemberToChannel(List<Long> idList) {

        for (Long id:idList) {
            EnterpriseSubmemberApply submember = enterpriseSubmemberApplyService.selectByPrimaryKey(id);
            MemberInfo memberInfo = null;
            if (submember.getMemberId() != null) {
                memberInfo = memberInfoService.selectByPrimaryKey(submember.getMemberId());
            }

            RcChannelApply channelApply = new RcChannelApply();
            channelApply.setChannelName(submember.getNickname());
            channelApply.setEnterpriseId(submember.getEnterpriseId());
            channelApply.setMemberId(memberInfo.getMemberId());
            channelApply.setPrincipal(memberInfo.getNickname());
            channelApply.setMobile(submember.getPhone());
            channelApply.setChannelType("1");
            channelApplyService.insertReturnId(channelApply);

            Map<String, Long> map = new HashMap<>();
            map.put("channelApplyId", channelApply.getChannelApplyId());
            mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map), 1);
        }
    }

    @Override
    public void updateSubmember(EnterpriseSubmember submember, Boolean createUser) {
        enterpriseSubmemberMapper.updateByPrimaryKeySelective(submember);
        TenantUser exitUser = tenantUserService.selectByMobile(submember.getSubmemberMobile());

        if (createUser == true && exitUser == null) {
            TenantUser user = new TenantUser();
            user.setTenantCode(submember.getTenantCode());
            user.setEnterpriseId(submember.getBelongEnterpriseId());
            user.setUserType("20");
            user.setLoginName(submember.getSubmemberMobile());
            user.setRealName(submember.getSubmemberName());
            user.setMobile(submember.getSubmemberMobile());
            user.setPassword(MD5Utils.encrypt(submember.getSubmemberMobile(), "123456"));
            tenantUserService.insertSelective(user);
        }
    }
}
